package com.wzp.yyptproject.until;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

@Component
public class RedisLock {
    @Autowired
    private RedisTemplate redisTemplate;
    public boolean lock(String key,String timestamp){
        if (redisTemplate.opsForValue().setIfAbsent(key,timestamp)){
            return true;
        }
        String curtimestamp = (String) redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(curtimestamp)&&Long.valueOf(curtimestamp)<System.currentTimeMillis()){
            String oldTimeStamp=(String)redisTemplate.opsForValue().getAndSet(key,timestamp);
            if (!StringUtils.isEmpty(oldTimeStamp)&&oldTimeStamp.equals(curtimestamp)){
                return true;
            }

        }
        return false;
    }
}
